<?php
namespace App\Http\Controllers;

use App\Models\Favourite;
use App\Models\MyMessage;

use App\Models\ActivityProject;
use App\Models\ActivityProjectVideo;
use App\Models\ActivityType;
use App\Models\ActivityVideoComment;
use App\Models\Project;
use App\Models\Zone;
use App\Models\Activity;
use App\Http\Controllers\Controller;
use \DB;
use Auth;
use Validator;
use Illuminate\Support\Facades\Request;
use App\Http\Requests\ActivityProjectVideoPostRequest;
use App\Models\User;
use App\Models\Tag;
use App\Models\VideoTag;


class ActivityProjectVideoController extends CommonController
{

    /**
     * 活动列表。
     *
     * @return Response
     */
    public function getIndex()
    {
        $datas = ActivityProjectVideo::with('activity', 'project')->orderBy('created_at', 'desc')->orderBy('top', 'desc')->orderBy('hot', 'desc')->orderBy('sort', 'asc')->orderBy('created_at', 'desc')->paginate(10);

        $return_datas = array();
        foreach($datas as $k=>$v){
            //加入收藏数
            $f_count = Favourite::where('model', 'video')->where('id', $v->id)->count();
            $v->f_count=$f_count;
            //加入评论数
            $c_count = ActivityVideoComment::where('post_id', $v->id)->count();
            $v->c_count=$c_count;
            $return_datas[] = $v;
        }

        return view('activityprojectvideo.index')->with("r_datas", $return_datas)->with("datas", $datas)->with("actions", $this->actions);
    }

    /**
     * 执行一个搜索
     */
    public function search()
    {
        $data = Request::all();
        $sql = ActivityProjectVideo::with('activity', 'project')->orderBy('top', 'desc')->orderBy('hot', 'desc')->orderBy('sort', 'asc')->orderBy('created_at', 'desc');
        if (isset($data['activity_name']) && $data['activity_name'] != '') {
            $aIds = Activity::where('subject', 'like', '%' . trim($data['activity_name']) . '%')->lists('id');
            $sql->whereIn('activity_id', $aIds);
        }

        if (isset($data['project_name']) && $data['project_name'] != '') {
            $pIds = Project::where('subject', 'like', '%' . trim($data['project_name']) . '%')->lists('id');
            $sql->whereIn('project_id', $pIds);
        }

        if (isset($data['video_name']) && $data['video_name'] != '') {
            $sql->where('subject', 'like', '%' . trim($data['video_name']) . '%');
        }


        if (isset($data['wonderful']) && $data['wonderful'] != '') {
            $sql->where('wonderful', $data['wonderful']);
        }

        $lists = $sql->paginate(10);

        $return_datas=array();
        foreach($lists as $k=>$v){
            //加入收藏数
            $f_count = Favourite::where('model', 'video')->where('id', $v->id)->count();
            $v->f_count=$f_count;
            //加入评论数
            $c_count = ActivityVideoComment::where('post_id', $v->id)->count();
            $v->c_count=$c_count;
            $return_datas[] = $v;
        }


        return view('activityprojectvideo.search')->with('lists', $lists)->with("r_datas", $return_datas)
            ->with('activity_name', trim($data['activity_name']))
            ->with('project_name', trim($data['project_name']))
            ->with('video_name', trim($data['video_name']))->with('wonderful', $data['wonderful'])
            ->with('actions', $this->actions);
    }

    /**
     * 活动添加页面
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getCreate()
    {
        $activities = DB::table('activity')->where('status', 1)->select('id', 'subject')->get();
        $activity_type = ActivityType::get();

//        dd($activity_type);

        return view('activityprojectvideo/create')->with('activities', $activities)->with('activity_type', $activity_type);
    }

    /**
     * 添加视频
     *
     * @return string
     */
    public function postInsert(ActivityProjectVideoPostRequest $request)
    {
        $data = Request::all();
        $data['pubdate'] = time();
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $data['path'] = $data['app_path'];
        $tag = $data['tag'];

        if ($data['uid'] == '') {
            unset($data['uid']);
        }

        unset($data['user_search'], $data['tag']);

        $id = DB::table("activity_project_video")->insertGetId($data);

        //插入标签
        if ($tag != '') {
            $existTags = Tag::lists('name')->toArray();
            $tags = explode(',', str_replace('，',',', $tag));
            //剔除可能出现的连续两个逗号
            $tags = array_filter($tags, function($v){if($v==''){ return false;} else{ return true;}});
            $tags = array_map(function($v){return trim($v);}, $tags);

            foreach ($tags as $k => $v) {
                if (!in_array(trim($v), $existTags)) {
                    $result = Tag::create(['name' => trim($v)]);
                    VideoTag::create(['video_id'=>$id, 'tag_id'=>$result->id ]);
                } else {
                    $result = Tag::where('name', trim($v))->first();
                    VideoTag::create(['video_id'=>$id, 'tag_id'=>$result->id ]);
                }
            }
        }

        if (isset($data['project_id']) && $data['project_id'] > 0) {
            Project::where('id', $data['project_id'])->update(['is_roadshow_video' => 1]);
            $project=Project::where('id',$data['project_id'])->first();
            $activity=Activity::where('id',$data['activity_id'])->first();
            $m_title='恭喜您的项目视频已上传。';
            $m_content='你的项目相关路演视频已更新并发布至无界投融平台，你可以在应用端首页浏览相应视频，并分享给你的小伙伴们，畅想无界投融高清跨域路演，感受最具互联网思维的创投体验，为自己代言~';
            MyMessage::createMessage($project->uid,$m_title,'tourong',$m_content,'','');
            $m_title='无界投融新增了很多项目路演，和活动路演，快来加入我们吧！';
            $m_content='投融小秘书又新添了不少视频哦~快来看看有没有你感兴趣的路演项目以及创业课程。';
            MyMessage::createMessage(0,$m_title,'official',$m_content,'','','all');
        }
        if ($id) {
            return AjaxCallbackMessage('活动视频添加成功', true, url('activityprojectvideo/index'));
        } else {
            return AjaxCallbackMessage('活动视频添加失败', false);
        }
    }

    /**
     * 编辑活动
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getEdit()
    {
        if (!Request::has('vid')) {
            return $this->tip('参数异常', url('activityprojectvideo/index'), false);
        }
        $vid = Request::input('vid');
//        $activities = DB::table('activity')->where('status', 1)->select('id', 'subject')->get();
        $video = DB::table('activity_project_video')->where('id', $vid)->first();
        $activity_type = ActivityType::get();
        $nowType = ActivityType::where('code', $video->activity_type)->first();
        $activities = Activity::where('type', $nowType->code)->get();
        $projects = ActivityProject::with('project')->where('activity_id', $video->activity_id)->get();
        $user = User::where('uid', $video->uid)->first();


        $tags = VideoTag::with('tag')->where('video_id', $vid)->get();
        $tagNames = array();
        foreach($tags as $k=>$v){
            isset($v->tag) && $tagNames[] = $v->tag->name;
        }
        $tagNames = implode(',', $tagNames);

        return view('activityprojectvideo.edit')->with("video", $video)
            ->with('activities', $activities)->with('activity_type', $activity_type)->with('tagNames', $tagNames)
            ->with('nowType', $nowType)->with('projects', $projects)->with('user', $user)->with('user', $user);
    }

    /**
     * 编辑活动
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getDetail()
    {
        if (!Request::has('vid')) {
            return $this->tip('参数异常', url('activityprojectvideo/index'), false);
        }
        $vid = Request::input('vid');
        $activities = DB::table('activity')->where('status', 1)->select('id', 'subject')->get();
        $video = DB::table('activity_project_video')->where('id', $vid)->first();

        return view('activityprojectvideo.detail')->with("video", $video)->with('activities', $activities);
    }

    /**
     * 更新角色信息
     *
     * @return string
     */
    public function postUpdate(ActivityProjectVideoPostRequest $request)
    {
        $data = Request::all();
        $vid = $data['id'];
//        $data['pubdate'] = time();
        $data['updated_at'] = time();
        $data['created_at'] = strtotime($data['created_at']);

        $data['path'] = $data['app_path'];
        $tag = $data['tag'];

        if ($data['uid'] == '') {
            unset($data['uid']);
        }
        unset($data['id'], $data['user_search'], $data['tag']);

        DB::table("activity_project_video")->where('id', $vid)->update($data);

        $tags = explode(',', str_replace('，',',', $tag));
        //剔除可能出现的连续两个逗号
        $tags = array_filter($tags, function($v){if($v==''){ return false;} else{ return true;}});

        //剔除管理员无心输入的空格
        $tags=array_map(function ($v){return trim($v);}, $tags);

        $nowTags = VideoTag::with('tag')->where('video_id', $vid)->get();
        $tagNames = array();
        foreach($nowTags as $k=>$v){
            isset($v->tag) && $tagNames[] = $v->tag->name;
        }
        //获取需要删除的关键字
        $del = array_diff($tagNames, $tags);
        $delIds = array_map(function ($v){$result = Tag::where('name',$v)->first(); return $result->id;}, $del);
        foreach($delIds as $v){
            VideoTag::where('video_id', $vid)->where('tag_id', $v)->delete();
        }
        //获取需要新增的关键字
        $add = array_diff($tags, $tagNames);
        if (count($add)!=0) {
            $existTags = Tag::lists('name')->toArray();
            foreach ($add as $k => $v) {
                if (!in_array(trim($v), $existTags)) {
                    $result = Tag::create(['name' => trim($v)]);
                    VideoTag::create(['video_id'=>$vid, 'tag_id'=>$result->id ]);
                } else {
                    $result = Tag::where('name', trim($v))->first();
                    VideoTag::create(['video_id'=>$vid, 'tag_id'=>$result->id ]);
                }
            }
        }

        return AjaxCallbackMessage('活动编辑成功', true, url('activityprojectvideo/index'));
    }

    /**
     * 删除活动
     *
     * @return string
     */
    public function postDelete()
    {
        if (!Request::has('vid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $vid = Request::input("vid");
        DB::table('activity_project_video')->where('id', '=', $vid)->delete();

        return AjaxCallbackMessage('活动视频删除成功', true, url('activityprojectvideo/index'));
    }

    /**
     * 活动项目列表。
     *
     * @return Response
     */
    public function postActivityprojects()
    {
        $aid = Request::input('aid');
        $datas = DB::table('activity_project as ap')->join("activity as a", "ap.activity_id", "=", "a.id")->join("project as p", "ap.project_id", "=", "p.id")->where(
            'ap.activity_id',
            intval($aid)
        )->select("p.id", "p.subject")->get();

        return AjaxCallbackMessage($datas, true);
    }

    /**
     * 通过活动类型来获取活动
     */
    public function postSearchActivity(Request $request)
    {
        $data = $request::input();
        $result = Activity::where('type', trim($data['activity_type']))->get();
//        dd($result);

        if (count($result)) {
            return AjaxCallbackMessage($result, true);
        } else {
            return AjaxCallbackMessage('没有与该类型匹配的活动！', false);
        }
    }


}